/*
 * -------------------------------------------------------------------------------------------------------*
 * SBS Priceboard V2.0
 * Copyright (C) 2008 Unicom Vietnam JSC
 * -------------------------------------------------------------------------------------------------------* 
 * HeadURL: http://192.168.1.4/svn/priceboard/trunk/SBS_PriceboardV2/front-end/end-user/enduser_priceboard/
 * LastChangeBy:
 * LastChangeDate:
 */
package com.unicom.priceboard.data.hose;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.unicom.priceboard.data.vo.TotalMarketElement;
import com.unicom.priceboard.thread.TotalMarketThread;
import com.unicom.priceboard.util.Util;


/**
 * Creation date: Jul 16, 2008
 * @author quan
 */
public class TotalMarketReader {
	public static int prev=0;
	public static int idxBegin_T2=0;
	public static int idxBegin_T3=0;
	public static int idxBegin_T4=0;
	private static final Logger logger = Logger.getLogger(TotalMarketReader.class);
	
	public void Totalmarket(String path){
		try{
			FileInputStream instrTotalMarket = new FileInputStream(Util.getCurrentDataPath(path));
			parseTotalMarket(instrTotalMarket);
			instrTotalMarket.close();
		}catch(Exception e){
			logger.debug("not read file: "+e.getMessage());
		}
	}
	private void parseTotalMarket(InputStream is) {
		List<TotalMarketElement> records = new ArrayList<TotalMarketElement>();
		DataInputStream input = new DataInputStream(is);
		try {
			while (input.available()>0) {
				//System.out.println("parsing.....");
				TotalMarketElement record = new TotalMarketElement();
				// Create a new ByteBuffer to store a record from file
				ByteBuffer buf = ByteBuffer.allocate(68);
				// Set to little endian
				buf.order(ByteOrder.LITTLE_ENDIAN);
				// Get each field from the file and put it to the byte buffer
				buf.putInt(input.readInt()); // SetIndex
				buf.putInt(input.readInt()); // TotalTrade
				buf.putDouble(input.readDouble()); // TotalShare
				buf.putDouble(input.readDouble()); // TotalValue
				buf.putDouble(input.readDouble()); // UpVolume
				buf.putDouble(input.readDouble()); // NoChangeVolume (doi cho voi DownVolume trong file moi)
				buf.putDouble(input.readDouble()); // DownVolume (doi cho voi NoChangeVolume trong file moi)
				buf.putShort(input.readShort()); // Advances
				buf.putShort(input.readShort()); // NoChange (doi cho voi Declines trong file moi)
				buf.putShort(input.readShort()); // Declines (doi cho voi NoChange trong file moi)
				buf.putInt(input.readInt()); // Set50Index
				buf.put(input.readByte()); // MarketId
				buf.put(input.readByte()); // Filler
//				for (int i = 0; i < 8; i++)
//					buf.put(input.readByte()); // Time (Old File)
//				for (int i = 0; i < 4; i++)
//					buf.put(input.readByte()); // Time
				buf.putInt(input.readInt());
				// Reset position for reading
				buf.flip();
				// Set to big endian
				buf.order(ByteOrder.BIG_ENDIAN);

				// Retrieve data from byte buffer
				record.setSetIndex(buf.getInt());
				record.setTotalTrade(buf.getInt());
				record.setTotalShare(buf.getDouble());
				record.setTotalValue(buf.getDouble());
				record.setUpVolume(buf.getDouble());
				record.setNoChangeVolume(buf.getDouble());
				record.setDownVolume(buf.getDouble());
				record.setAdvances(buf.getShort());
				record.setNoChange(buf.getShort());
				record.setDeclines(buf.getShort());
				record.setSet50Index(buf.getInt());
				record.setMarketId((char) buf.get());
				record.setFiller((char) buf.get());

//				StringBuffer time = new StringBuffer();
//				for (int i = 0; i < 8; i++)
//					time.append((char) buf.get()); //(Old File)
//				for (int i = 0; i < 4; i++)
//					time.append((char) buf.get());
				
//				record.setTime(String.valueOf(buf.getInt()));
				record.setTime(String.valueOf(buf.getInt()));
				records.add(record);
				
				if(Integer.parseInt(record.getTime())>=90000 && prev==0){
					prev=records.get(0).getSetIndex();
				}
				if(idxBegin_T2==0 && Integer.parseInt(record.getTime())>=90000)	{
					//System.out.println("start session 2...");
					double totalshare=records.get(records.size()-1).getTotalShare();
					if(totalshare!=0) {	
						//TotalMarketThread.mapTotalMarket.put(2,records.get(records.size()-1));
						idxBegin_T2 = records.size()-1;
						TotalMarketThread.mapTotalMarket.put(1,records.get(idxBegin_T2));
						TotalMarketThread.mapTotalMarket.put(5,records.get(idxBegin_T2));
					}//data for session 1					
				}else if(idxBegin_T3==0 && Integer.parseInt(record.getTime())>=101500) {
					//Start session 3,the lastest of session 2 is update. and session 5 is two
					//System.out.println("start session 3...");
					idxBegin_T3 = records.size()-1;
					TotalMarketThread.mapTotalMarket.put(2,records.get(idxBegin_T3));
					TotalMarketThread.mapTotalMarket.put(5,records.get(idxBegin_T3));
									
				}else if(idxBegin_T4==0 && Integer.parseInt(record.getTime())>=103000) {
					//System.out.println("start session 4...");
					//start session 4 update session 3 and session 5
					if(TotalMarketThread.mapTotalMarket.get(2)!=null){
						if(records.get(records.size()-1).equals(TotalMarketThread.mapTotalMarket.get(2)))
							continue;
					}					
					idxBegin_T4 = records.size()-1;
					TotalMarketThread.mapTotalMarket.put(4,records.get(idxBegin_T4));
					TotalMarketThread.mapTotalMarket.put(3,records.get(idxBegin_T4));
					TotalMarketThread.mapTotalMarket.put(5,records.get(idxBegin_T4));
				}
				if(Integer.parseInt(records.get(records.size()-1).getTime())>103000 &&Integer.parseInt(records.get(records.size()-1).getTime())<=110500){
					//System.out.println("start session 5...");
						//if(Integer.valueOf(GetMarketStatusThread.getCurrentMarketState())==4||idxBegin_Pt==0){	
					if(TotalMarketThread.mapTotalMarket.get(4)!=null){
						if(Integer.parseInt(TotalMarketThread.mapTotalMarket.get(4).getTime())<Integer.parseInt(record.getTime())) {
							int index=records.size()-1;
							TotalMarketThread.mapTotalMarket.put(4,records.get(index));
							TotalMarketThread.mapTotalMarket.put(5,records.get(index));					
						}
					}
				}	
				//session 2
				if(idxBegin_T3==0 && Integer.parseInt(record.getTime())>90000 && Integer.parseInt(record.getTime())<=101500){
					//System.out.println("start session 2-2...");
					if(TotalMarketThread.mapTotalMarket.get(2)!=null){
						if(Integer.parseInt(TotalMarketThread.mapTotalMarket.get(2).getTime())<Integer.parseInt(record.getTime())) {
							TotalMarketThread.mapTotalMarket.put(2,record);
							TotalMarketThread.mapTotalMarket.put(5,record);
						}
					}else {
						if(idxBegin_T2<records.size()-1)
							TotalMarketThread.mapTotalMarket.put(2, record);
							TotalMarketThread.mapTotalMarket.put(5,record);
					}
				}
				
			}//end while
			//Current index always is the last record
			int size = records.size();
			while(size > 0) {
				TotalMarketElement element = records.get(size - 1);
				//data may be incorrect, so we get the previous one
				if (null != element && element.getSetIndex() != 0) {
					TotalMarketThread.setCurrentTotalMarket(element);
					break;
				} else {
					size = size - 1;
				}
			}
//			TotalMarketElement element = TotalMarketThread.getCurrentTotalMarket();
//			System.out.println("Current market in parser:" +element.getSetIndex() + " Time:" +element.getTime());
			//System.out.println("end parsing !");
			
		} catch (Exception ex) {
			logger.debug("*****parsing TotalMarket process error :\n"+ex.getMessage());
			System.out.println("parsing error: " );
			ex.printStackTrace();
		}
	}
}
